<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
		<cl-pagefull @resize="onResize">
			<template #head>
				<cl-title-module
					title="部门报表"
					sub-title="以部门人员为单位进行汇总（当前登陆账号所管理的部门）"
					:columns="initColumns"
					:print="printParams"
					v-model="table.columns"
					@export-file="exportExcel"
				/>
				<el-row type="flex">
					<cl-filter-group v-model="search">
						
						<cl-filter label="事业部">
							<cl-select
								v-model="search.biz_id"
								placeholder="请选择"
								filterable
								@change="changeBiz"
							>
								<el-option
									v-for="item in business"
									:key="item.biz_id"
									:label="item.biz_name"
									:value="item.biz_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="时间">
							<cl-date-picker
								v-model="search.date"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								style="width: 230px"
								:clearable="false"
							/>
						</cl-filter>
						<cl-filter label="门店">
							<cl-shop-select
								v-model="search.dept_id"
								placeholder="请选择"
								filterable
								style="width: 150px"
								clearable
								@change="changeDept"
								show-all
								:biz_id="search.biz_id"
							/>
						</cl-filter>
						<cl-filter label="产品仓库编码">
							<el-input
								v-model="search.product_number"
								placeholder="请输入产品仓库编码"
								clearable
							/>
						</cl-filter>
					</cl-filter-group>
				</el-row>
			</template>
			<cl-table v-bind="table" id="deptReport" ref="table">

			</cl-table>

			<!-- 数据表格 -->
		</cl-pagefull>
	</cl-crud>
</template>
<script>
import { exportExcel } from "@/utils/excel";
import { cloneDeep } from "cl-admin/utils";
import dayjs from "dayjs";
import { last } from "cl-admin/utils";
import { delEmptyChildren } from "@/utils";

export default {
	data() {
		return {
			printParams: {
				id: "deptReport",
				popTitle: "部门报表"
			},
			// 表格配置
			table: {
				"context-menu": ["refresh"],
				columns: [],
				props: {
					maxHeight: 500,
					showSummary: true
					// summaryMethod: this.getSummaries
				}
			},
			initColumns: [],
			search: {
				date: [
					dayjs()
						.startOf("day")
						.format("YYYY-MM-DD"),
					dayjs()
						.endOf("day")
						.format("YYYY-MM-DD")
				],
				biz_id: "",
				dept_id: '',
                product_number: ""
				// dept_id:''
			},
			deptList: [], //部门
			userList: [] //组员
		};
	},
	computed: {
		bizRefData() {
			let { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	created() {
		this.search.biz_id = this.getCurrBiz();
		this.init();
	},
	methods: {
		onLoad({ ctx, app }) {
			ctx.service(this.$service.erp)
				.set("dict", {
					api: {
						page: "deptReport"
					}
				})
				.done();
			app.refresh(this.search);
		},
		async onRefresh(params, { next, done, render }) {
			let { title, data } = await next(params);
			let columns = (title ?? []).map((v, i) => {
				return {
					disable: i == 0,
					fixed: i == 0,
					prop: v.key,
					label: v.name,
					minWidth: 170,
					sortable: true
				};
			});
			this.initColumns = columns;
			!this.table.columns.length && (this.table.columns = columns);
			render(data);
		},
		async init(type = 0) {
			const { biz_id } = this.search;
            this.getBizRefShop(biz_id);
			this.initData(type);
		},
		async initData(type = 0) {
			const { biz_id } = this.search;

			this.deptList = delEmptyChildren(
				(await this.$store.dispatch("common/getDept", {
					biz_id,
					post: 2,
					needAll: false,
					needCascader: true
				})) || []
			);
			this.changeDept(type);
		},
		//切换事业部
		changeBiz() {
			this.search.company_id = "";
			this.search.bra_id = [];
			// this.search.dept_id = "";
			this.search.dept_id = [];
			this.init(1);
		},
		//切换部门
		changeDept(type) {
			// this.getManageDeptUser();
			if (type) {
				// this.refresh();
			}
		},
		// crud刷新
		refresh() {
			this.$refs.crud.refresh({ page: 1, ...this.search });
			this.$nextTick(() => {
				this.$refs.table?.calcMaxHeight?.();
			});
		},
		onResize(h) {
			this.table.props.maxHeight = h;
		},
		// 表格合计
		getSummaries({ columns, data }) {
			let number_visitors = 0,
				shop_deposit = 0,
				number_visitors_new = 0,
				presale_deposit_new_people = 0;
			let arr = ["otn_arrival_rate", "manage_shop"];
			return columns.map((column, index) => {
				if (index === 0) {
					return "合计";
				}
				if (arr.includes(column.property)) return "";
				if (column.property === "new_arrival_rate") {
					if (presale_deposit_new_people) {
						let result = number_visitors_new / presale_deposit_new_people;
						return this.toFixed(result * 100) + "%";
					} else {
						return 0 + "%";
					}
				}
				if (column.property === "arrival_rate") {
					if (shop_deposit) {
						let result = number_visitors / shop_deposit;
						return this.toFixed(result * 100) + "%";
					} else {
						return 0 + "%";
					}
				}
				const values = data.map(item => Number(item[column.property]));
				let sum = values.reduce((prev, curr) => {
					const value = Number(curr);
					if (!isNaN(value)) {
						return prev + curr;
					}
					return prev;
				}, 0);
				if (column.property === "number_visitors_new") {
					number_visitors_new = sum;
				}
				if (column.property === "number_visitors") {
					number_visitors = sum;
				}
				if (column.property === "shop_deposit") {
					shop_deposit = sum;
				}
				if (column.property === "presale_deposit_new_people") {
					presale_deposit_new_people = sum;
				}
				return this.toFixed(sum);
			});
		},
		// 获取组员
		// async getManageDeptUser() {
		// 	let { biz_id } = this.search;
		// 	let dept_id = this.search.dept_ids.join();
		// 	this.userList = [];
		// 	const data = await this.$service.user.deptuserlists({
		// 		biz_id,
		// 		dept_id,
		// 		post: 2,
		// 		manage_user: 1
		// 	});
		// 	this.userList = data;
		// },
		// 导出EXCEl
		exportExcel() {
			exportExcel("#deptReport");
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-table--scrollable-x {
		.el-table__body-wrapper {
			z-index: 2;
		}
	}
}
</style>
